import threading, time, os



APPLICATION_STORAGE_PATH = "docker_engine/applications/"



# Collecting Docker container's running metric
class MetricsCollector(threading.Thread):
    def __init__(self, docker_client, container_name):
        threading.Thread.__init__(self)
        self.container_name = container_name
        self.metrics_generator = docker_client.stats(container_name, decode=True)
        self.metrics = None

        self.setDaemon(True)

    def run(self):
        for m in self.metrics_generator:
            self.metrics = m

    def analyze(self):
        return self.metrics["cpu_stats"]["system_cpu_usage"]



# save uploaded file to local disk
def handle_uploaded_file(upload_file, file_path):
    with open(file_path, 'wb+') as destination:
        for chunk in upload_file.chunks():
            destination.write(chunk)



# create application folder in local disk
def handle_application_creation(application_name, definition_file):
    application_folder = APPLICATION_STORAGE_PATH + application_name
    os.mkdir(application_folder)
    definition_file_path = application_folder+"/"+"docker-compose.yml"
    handle_uploaded_file(definition_file, definition_file_path)
    return definition_file_path



# return static file to the user
def handle_static_file(file_path):
    with open(file_path) as f:
        content = f.read()
    return content



# base image or application image
def check_image_usage(repository):
    # define base container images
    BASE_IMAGES = ["ubuntu", "centos", "busybox"]

    usage = "A"
    for image in BASE_IMAGES:
        if image in repository:
            usage = "B"
            break
    return usage
